package org.example.pet.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.pet.common.expection.CustomException;
import org.example.pet.config.mq.EventPublisher;
import org.example.pet.dto.AdoptedEmailDTO;
import org.example.pet.dto.AdoptionApplyInfoDTO;
import org.example.pet.dto.AdoptionInfoResponseDTO;
import org.example.pet.dto.AdoptionPageQueryDTO;

import org.example.pet.mapper.AdoptionApplicationMapper;
import org.example.pet.pojo.AdoptionApplication;
import org.example.pet.pojo.Pet;

import org.example.pet.pojo.User;
import org.example.pet.service.AdoptionApplicationService;
import org.example.pet.service.PetService;
import org.example.pet.service.UserService;
import org.example.pet.vo.PageVO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class AdoptionApplicationServiceImpl extends ServiceImpl<AdoptionApplicationMapper, AdoptionApplication> implements AdoptionApplicationService {
    @Autowired
    private AdoptionApplicationMapper adoptionApplicationMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private PetService petService;
    @Autowired
    private EventPublisher publisher;
    
    @Override
    public void delete(Long adoptionApplicationId) {
        // 删除（在待审批状态下）
        LambdaQueryWrapper<AdoptionApplication> qw = new LambdaQueryWrapper();
        qw.eq(AdoptionApplication::getApplicationId, adoptionApplicationId);
        
        qw.eq(AdoptionApplication::getStatus, AdoptionApplication.StatusVal.PENDING.getVal());
        boolean isSuccess = this.remove(qw);
        if(!isSuccess) {
            throw new CustomException("审核状态不符，请联系管理员！");
        }
    }
    

    @Override
    public PageVO<AdoptionInfoResponseDTO> page(AdoptionPageQueryDTO queryDTO) {
        // 处理分页参数默认值
        int page = queryDTO.getPage() == null ? 1 : queryDTO.getPage();
        int pageSize = queryDTO.getPageSize() == null ? 7 : queryDTO.getPageSize();
        // 校验分页参数合法性
        page = Math.max(page, 1);
        pageSize = Math.max(pageSize, 1);
        pageSize = Math.min(pageSize, 100); 

        // 计算偏移量：offset = (当前页 - 1) * 每页条数
        int offset = (page - 1) * pageSize;
        queryDTO.setOffset(offset);
        // 回写处理后的参数，方便后续日志/校验
        queryDTO.setPage(page); 
        queryDTO.setPageSize(pageSize);

        // 查询分页数据列表
        List<AdoptionInfoResponseDTO> records = adoptionApplicationMapper.queryAdoptionList(queryDTO);
        // 查询总条数
        Long total = adoptionApplicationMapper.queryAdoptionCount(queryDTO);
        
        // 封装分页结果
        return new PageVO<>(records, total, page, pageSize);
    }

    @Override
    public AdoptionApplyInfoDTO getAdoptionApplyDetail(Long applicationId) {
        return adoptionApplicationMapper.getAdoptionApplyDetail(applicationId);
    }

    @Transactional
    @Override
    public void editAdoptionStatus(AdoptionApplication adoptionApplication) {
        // 修改申请状态
        adoptionApplication.setResponseDate(LocalDateTime.now());
        updateById(adoptionApplication);
        
        if(adoptionApplication.getStatus().equals(AdoptionApplication.StatusVal.APPROVED.getVal())) {   // 领养申请通过
            // 修改对应宠物状态
            Pet updatePet = new Pet();
            updatePet.setPetId(adoptionApplication.getPetId());
            updatePet.setStatus(Pet.StatusVal.UNAVAILABLE.getVal());
            // 查询用户信息
            Long userId = adoptionApplication.getUserId();
            User user = userService.getById(userId);
            AdoptedEmailDTO dto = new AdoptedEmailDTO();
            dto.setUsername(user.getUsername());
            dto.setToEmail(user.getEmail());
            petService.updateById(updatePet);

            // 其他申请了这个宠物的全部变为已拒绝
            // 查询其他申请了这个宠物的申请记录
            LambdaQueryWrapper<AdoptionApplication> wrapper = new LambdaQueryWrapper();
            wrapper.eq(AdoptionApplication::getPetId, adoptionApplication.getPetId());
            List<AdoptionApplication> applications = list(wrapper);
            for (AdoptionApplication application : applications) {
                if(application.getApplicationId() == adoptionApplication.getApplicationId()) {
                    continue;
                }
                adoptionApplicationMapper.updateStatusToRejected(application.getApplicationId());
            }

            // 发送消息
            publisher.publish("topic.adopt_success", JSON.toJSONString(dto));
        }
    }

    @Override
    public Long getApplyIdByPetId(Long petId) {
        LambdaQueryWrapper<AdoptionApplication> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdoptionApplication::getPetId, petId);
        wrapper.eq(AdoptionApplication::getStatus,  AdoptionApplication.StatusVal.APPROVED.getVal());
        AdoptionApplication application = getOne(wrapper);
        return application.getApplicationId();
    }

    @Override
    public boolean userIsAdoptingPet(Long userId, Long petId) {
        LambdaQueryWrapper<AdoptionApplication> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdoptionApplication::getUserId, userId);
        wrapper.eq(AdoptionApplication::getPetId, petId);
        wrapper.eq(AdoptionApplication::getStatus, AdoptionApplication.StatusVal.PENDING.getVal());
        AdoptionApplication application = getOne(wrapper);
        
        return application != null;
    }
}
